<template>
  <view class="address-edit">
    <custom-nav-bar title="地址管理" showBack></custom-nav-bar>
    <view class="form">
      <view class="form-item">
        <label>联系人:</label>
        <view class="input-sex">
          <input class="input" v-model="formData.consignee" type="text" placeholder="请输入联系人" />
          <view class="sex">
            <uni-data-checkbox v-model="sex" :localdata="sexList"></uni-data-checkbox>
          </view>
        </view>
      </view>
      <view class="form-item">
        <label>手机号:</label>
        <input class="input" v-model="formData.phone" type="number" placeholder="请输入手机号" />

      </view>
      <view class="form-item">
        <label>收货地址:</label>
        <input class="input" v-model="formData.detail" type="text" placeholder="请输入详细地址" />
      </view>
    </view>
    <button class="save-btn" @click="saveAddress">保存地址</button>
    <button class="delete-btn" v-if="action === 'edit'" @click="deleteAddress">删除地址</button>
    <show-modal :showModal="showM" :option="modalOptions"></show-modal>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { request } from '@/utils/request.js'; // 假设存在统一的请求封装文件
import { useAddress } from '@/stores/address.js'
import { onLoad } from '@dcloudio/uni-app';
import { apiGet } from '@/api/apis.js';

// 模态框显示或隐藏的状态
const showM = ref(false)

// 模态框的配置选项
const modalOptions = {
  title: '删除地址',
  content: '确认删除该地址吗？',
  showCancel: '取消',
  confirmText: '清除',
  success: function (res) {
    if (res.confirm) {
      uni.showToast({
        title: '地址删除成功',
        icon: 'none'
      });
      uni.navigateBack()
    }

    // 不论点击确定还是取消，都关闭模态框
    showM.value = false
  }
}





// 未连接到服务器时用于直接通过api的交互的凭证，连接到服务器时请删除
const res = { code: 200 }


const action = ref('edit')
const id = ref(null)
const store = useAddress()

// 表单数据
const formData = ref({
  consignee: '',
  phone: '',
  provinceCode: '',
  provinceName: '',
  cityCode: '',
  cityName: '',
  districtCode: '',
  districtName: '',
  detail: '',
  label: [],
  isDefault: 1,
  userId: ''
});

onLoad((options) => {
  // console.log(options);
  action.value = options.action

  // 为编辑时，更改渲染数据
  if (options.action === 'edit') {
    id.value = options.id;
    const arr = store.addressList.find(item => item.id == options.id)
    formData.value.consignee = arr.consignee;
    formData.value.phone = arr.phone;
    formData.value.detail = arr.company;

    // 添加userId
    formData.value.userId = options.id

  }
  else if (options.action === 'add') {

  }
})


const addressData = computed(() => ({ consignee: formData.value.consignee, phone: formData.value.phone, company: formData.value.detail, id: formData.value.userId, isDefault: formData.value.isDefault, sex: sex.value }))
// const data = computed(() => 123)

// 保存地址
const saveAddress = async () => {
  try {
    if (action.value === 'add') {

      // 对填写的内容进行校验
      if (!formData.value.consignee.trim() || !formData.value.phone.trim() || !formData.value.detail.trim()) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        });

        return
      }

      // // 与服务器交互接口
      // const res = await apiGet('/user/addressBook', formData.value, 'post');
      if (res.code === 200 || apiToken) {
        uni.showToast({
          title: '新增地址成功',
          icon: 'success'
        });
        uni.navigateBack();
      }

      // 同步本地数据
      store.addAddressList(addressData.value)

    } else if (action.value === 'edit') {

      // // 与服务器交互接口
      // const res = await await apiGet('/user/addressBook', formData.value, 'put');
      if (res.code === 200) {
        uni.showToast({
          title: '修改地址成功',
          icon: 'success'
        });
        uni.navigateBack();
      }

      console.log(addressData.value);

      // 同步本地数据
      store.editAddressList(addressData.value)
    }
  } catch (error) {
    console.error('保存地址失败', error);
    uni.showToast({
      title: '保存地址失败',
      icon: 'error'
    });
  }
};

// 删除地址
const deleteAddress = async () => {
  try {

    // // 与服务器交互接口
    // const res = await apiGet('/user/addressBook', { id }, 'delete');
    if (res.code === 200) {
      // uni.showToast({
      //   title: '删除地址成功',
      //   icon: 'success'
      // });
      // uni.showModal({
      //   title: '删除地址',
      //   content: '确定要删除地址吗？',
      //   success: function (res) {
      //     // uni.navigateBack();
      //     if (res.confirm) {
      //       uni.navigateBack();
      //     } else if (res.cancel) {

      //     }
      //   }
      // });
      showM.value = true
      // console.log(121212);

    }

    // console.log(formData.value.userId);
    // 同步本地数据
    store.deleteAddressList(id.value)
  } catch (error) {
    console.error('删除地址失败', error);
    uni.showToast({
      title: '删除地址失败',
      icon: 'error'
    });
  }
};

// onMounted(() => {
//   getAreaData();
//   if (action === 'edit') {
//     const getAddress = async () => {
//       try {
//         const res = await request.get(`/user/addressBook/${id}`);
//         if (res.code === 200) {
//           formData.value = {
//             ...formData.value,
//             ...res.data
//           };
//         }
//       } catch (error) {
//         console.error('获取地址详情失败', error);
//       }
//     };
//     getAddress();
//   }
// });



const sex = ref(0)


const sexList = ref([{
  text: '先生',
  value: 0
}, {
  text: '女士',
  value: 1
}])
</script>

<style scoped lang="scss">
.address-edit {
  padding: 10px;

  .form {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    // margin-bottom: 20px;

    .form-item {
      // margin-bottom: 10px;
      display: grid;
      grid-template-columns: 160rpx 1fr;
      height: 80rpx;
      line-height: 80rpx;

      label {
        display: block;
        margin-bottom: 5px;
        font-weight: bold;
      }

      .input {
        border: none;
        // background-color: red;
        height: 100%;
        border-bottom: 1px solid #ccc;

      }

      .input-sex {
        display: flex;

        .sex {
          display: flex;
          justify-content: center;
          align-items: center;
          margin-left: 20rpx;

        }
      }

    }
  }

  .save-btn {
    width: 100%;
    background-color: #e74747;
    color: white;
    // padding: 10px;
    border: none;
    border-radius: 5px;
    margin-top: 70rpx;
  }

  .delete-btn {
    width: 100%;
    background-color: #ccc;
    color: white;
    // padding: 10px;
    border: none;
    border-radius: 5px;
    margin-top: 10px;
  }
}
</style>
<style>
::v-deep .checklist-group {
  flex-direction: row !important;
  flex-wrap: nowrap !important;
  gap: 20rpx;
}

::v-deep .uni-label-pointer {
  margin: 0 !important;
  flex-wrap: nowrap !important;
}

::v-deep .checklist-text {
  white-space: nowrap !important;
}
</style>